import pillow_heif as ph
from PIL import Image
import os


def convert_heic_to_jpg(src, dest_dir):
    pi = ph.open_heif(src)
    for i, this_img in enumerate(pi):
        this_img = this_img.to_pillow()
        this_img = this_img.resize((2560, 2560), resample=Image.LANCZOS)
        this_img = this_img.crop((0, 560, 2560, 2000))
        this_img.save(os.path.join(dest_dir, "{}.jpg".format(i + 1)))


if __name__ == "__main__":
    files = [f for f in os.listdir(".") if f.endswith(".heic")]
    for f in files:
        theme, ext = os.path.splitext(f)
        theme = theme.strip().replace(" ", "-").lower()
        print("Converting {}...".format(theme))
        if not os.path.exists(theme):
            os.makedirs(theme)
        convert_heic_to_jpg(f, theme)
